package net1;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Request {
    //操作类型：1（展示目录文件列表），2（文件重命名），3（删除文件），4（上传文件），5（下载文件）
    private Integer type;
    private String url;
    private String data;

    //服务端解析请求时：根据约定好的格式来解析
    public static Request serverParse(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        Request request = new Request();
        request.type = Integer.parseInt(bufferedReader.readLine());
        request.url = bufferedReader.readLine();
        List<Character> list = new ArrayList<>();
        while (true) {
            char c = (char) bufferedReader.read();
            if (c == '\3') {
                break;
            }
            list.add(c);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : list) {
            stringBuilder.append(c);
        }
        request.data = stringBuilder.toString();
        return request;
    }

    //客户端发送请求到服务器
    public void clientWrite(OutputStream outputStream) {
        PrintWriter printWriter = new PrintWriter(outputStream);
        printWriter.println(type);
        printWriter.println(url);
        printWriter.write(data + "\3");
        printWriter.flush();
    }

    @Override
    public String toString() {
        return "Request{" +
                "type=" + type +
                ", url='" + url + '\'' +
                ", data='" + data + '\'' +
                '}';
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}
